package ly;

import java.util.ArrayList;
import java.util.List;

import aloha.activity.Activity;
import aloha.activity.NavActivity;
import aloha.base.Util.StringUtil;
import aloha.lv.Anim;
import aloha.lv.Color;
import aloha.lv.Cont;
import aloha.lv.Disp;
import aloha.lv.Font;
import aloha.lv.Label;
import aloha.lv.Obj;
import aloha.lv.Page;
import aloha.lv.Pic;
import aloha.lv.PicSrc;
import aloha.lv.Slider;
import aloha.lv.Textarea;
import aloha.lv.Obj.Event;
import aloha.lv.Obj.State;
import aloha.ui.display.PictureLoader;
import aloha.ui.widget.MateButton;

import java.io.File;
import java.io.IOException;
import java.util.List;

class ListItem {
    public String name;
    public int type; // 0 audio; 1 file; 2 dir

    public Obj bg;
    public Pic icon;
    public Label nameLabel;

    public void setPlayingStyle(boolean en) {
        if (nameLabel == null) {
            //列表页面切换走，控件就被删除了
            return;
        }
        if (en) {
            nameLabel.setTextColor(Color.make(0x84F705));
        } else {
            nameLabel.setTextColor(Color.make(0x5B8C25));
        }
    }

    public void delete() {
        bg.delete();
        bg = null;
        icon = null;
        nameLabel = null;
    }
}

public class HomeActivity extends Activity implements Obj.EventListener, AudioPlayer.Listener {
    AudioPlayer audioPlayer = null;
    boolean startAutomate = false;
    ListItem playItem = null;
    List<ListItem> playList = null;
    List<ListItem> playAudioList = null;
    List<ListItem> dispList = null;
    List<ListItem> dispAudioList = null;

    String currentPath = null;
    String playingPath = null;

    Pic bgPic;
    Pic titleIconPic;
    Label titleLabel;
    Label rateLabel;
    Label bpsLabel;

    Label startTimeLabel;
    Label endTimeLabel;
    Slider slider;

    Obj toolbarBg;
    Pic prevBtn, nextBtn, playBtn;
    Pic wavBtn, listBtn;

    Obj pathBg;
    Textarea pathText;
    Pic retBtn, okBtn;

    Obj tabBg;
    Obj wavBg, listBg;
    Page listPage;
    List<Obj> wavBars;
    @Override
    public void onCreate() {
        super.onCreate();
        Obj parent = getContent();

        bgPic = new Pic(parent);
        bgPic.setSrc(PicSrc.loadFile(Icon.getPath("gradient_1000_500.png")));
        bgPic.setPosition(0, 0);
        // bgPic.setSize(parent.getWidth(), 140);
        
        titleIconPic = new Pic(parent);
        titleIconPic.setSrc(PicSrc.loadFile(Icon.getPath("lxplayer.png")));
        titleIconPic.setPosition(10, 10);

        titleLabel = new Label(parent);
        titleLabel.setTextFont(Font.defaultFont(16, null));
        titleLabel.setText("刘德华-练习.mp3");
        titleLabel.align(titleIconPic, Obj.Align.OUT_RIGHT_MID, 10, 0);

        rateLabel = new Label(parent);
        rateLabel.setTextFont(Font.defaultFont(12, null));
        rateLabel.setText("44.1KHz");
        rateLabel.align(titleLabel, Obj.Align.OUT_RIGHT_MID, 10, 0);
        rateLabel.setBgColor(Label.PART_MAIN, Obj.State.DEFAULT, Color.BLACK);
        rateLabel.setBgOpa(Label.PART_MAIN, Obj.State.DEFAULT, 100);
        rateLabel.setTextColor(Color.WHITE);

        bpsLabel = new Label(parent);
        bpsLabel.setTextFont(Font.defaultFont(12, null));
        bpsLabel.setText("128Kbps");
        bpsLabel.align(rateLabel, Obj.Align.OUT_RIGHT_MID, 10, 0);
        bpsLabel.setBgColor(Label.PART_MAIN, Obj.State.DEFAULT, Color.BLACK);
        bpsLabel.setBgOpa(Label.PART_MAIN, Obj.State.DEFAULT, 100);
        bpsLabel.setTextColor(Color.WHITE);


        startTimeLabel = new Label(parent);
        startTimeLabel.setTextFont(Font.defaultFont(12, null));
        startTimeLabel.setText("1:23");
        startTimeLabel.align(null, Obj.Align.IN_TOP_LEFT, 10, 70);
        startTimeLabel.setBgColor(Label.PART_MAIN, Obj.State.DEFAULT, Color.BLACK);
        startTimeLabel.setBgOpa(Label.PART_MAIN, Obj.State.DEFAULT, 100);
        startTimeLabel.setTextColor(Color.WHITE);

        endTimeLabel = new Label(parent);
        endTimeLabel.setTextFont(Font.defaultFont(12, null));
        endTimeLabel.setText("4:30");
        endTimeLabel.align(null, Obj.Align.IN_TOP_RIGHT, -10, 70);
        endTimeLabel.setBgColor(Label.PART_MAIN, Obj.State.DEFAULT, Color.BLACK);
        endTimeLabel.setBgOpa(Label.PART_MAIN, Obj.State.DEFAULT, 100);
        endTimeLabel.setTextColor(Color.WHITE);

        slider = new Slider(parent);
        slider.setSize(endTimeLabel.getX() - (startTimeLabel.getX() + startTimeLabel.getWidth()), 10);
        slider.align(startTimeLabel, Obj.Align.OUT_RIGHT_MID, 0, 0);
        slider.setEventListener(this);

        toolbarBg = new Obj(parent);
        toolbarBg.setSize(parent.getWidth(), 30);
        toolbarBg.setBgColor(Label.PART_MAIN, Obj.State.DEFAULT, Color.WHITE);
        toolbarBg.setBgOpa(Label.PART_MAIN, Obj.State.DEFAULT, 100);
        toolbarBg.setPosition(0, 100);

        prevBtn = new Pic(toolbarBg);
        prevBtn.setSrc(PicSrc.loadFile(Icon.getPath("ic_prev.png")));
        prevBtn.align(null, Obj.Align.IN_LEFT_MID, 10, 0);
        prevBtn.setEventListener(this);

        playBtn = new Pic(toolbarBg);
        playBtn.setSrc(PictureLoader.loadFitDPI(Main.app, "ic_play.png"));
        playBtn.align(prevBtn, Obj.Align.OUT_RIGHT_MID, 10, 0);
        playBtn.setEventListener(this);

        nextBtn = new Pic(toolbarBg);
        nextBtn.setSrc(PicSrc.loadFile(Icon.getPath("ic_next.png")));
        nextBtn.align(playBtn, Obj.Align.OUT_RIGHT_MID, 10, 0);
        nextBtn.setEventListener(this);

        listBtn = new Pic(toolbarBg);
        listBtn.setSrc(PicSrc.loadFile(Icon.getPath("ic_list.png")));
        listBtn.align(null, Obj.Align.IN_RIGHT_MID, -10, 0);
        listBtn.setEventListener(this);

        wavBtn = new Pic(toolbarBg);
        wavBtn.setSrc(PicSrc.loadFile(Icon.getPath("ic_mode.png")));
        wavBtn.align(listBtn, Obj.Align.OUT_LEFT_MID, -10, 0);
        wavBtn.setEventListener(this);

        pathBg = new Obj(parent);
        pathBg.setSize(parent.getWidth(), 30);
        pathBg.setBgColor(Label.PART_MAIN, Obj.State.DEFAULT, Color.WHITE);
        // pathBg.setBgOpa(Label.PART_MAIN, Obj.State.DEFAULT, 100);
        pathBg.setPosition(0, 130);

        retBtn = new Pic(pathBg);
        retBtn.setSrc(PicSrc.loadFile(Icon.getPath("ic_prev.png")));
        retBtn.align(null, Obj.Align.IN_LEFT_MID, 10, 0);
        retBtn.setEventListener(this);

        okBtn = new Pic(pathBg);
        okBtn.setSrc(PicSrc.loadFile(Icon.getPath("dillo.png")));
        okBtn.align(null, Obj.Align.IN_RIGHT_MID, -10, 0);
        okBtn.setEventListener(this);

        pathText = new Textarea(pathBg);
        pathText.setFit(Cont.Fit.NONE);
        pathText.setOneLine(true);
        pathText.setScrollbarMode(Page.ScrollbarMode.OFF);
        pathText.setSize(okBtn.getX() - (retBtn.getX() + retBtn.getWidth()), 28);
        pathText.setText("/home/dalink/");
        pathText.align(retBtn, Obj.Align.OUT_RIGHT_MID, 0, 0);
        pathText.setTextFont(Textarea.PART_MAIN, Obj.State.DEFAULT, Font.defaultFont(12, null));

        tabBg = new Obj(parent);
        tabBg.setSize(parent.getWidth()*2, parent.getHeight() - (pathBg.getY() + pathBg.getHeight()));
        tabBg.align(null, Obj.Align.IN_BOTTOM_MID, 0, 0);
        tabBg.setX(-tabBg.getWidth()/2);

        wavBg = new Obj(tabBg);
        wavBg.setSize(tabBg.getWidth(), tabBg.getHeight());
        wavBg.setBgColor(Obj.PART_MAIN, Obj.State.DEFAULT, Color.make(0,0,0));
        wavBg.align(null, Obj.Align.CENTER, 0, 0);
        wavBg.setX(0);

        listBg = new Obj(tabBg);
        listBg.setBgColor(Obj.PART_MAIN, Obj.State.DEFAULT, Color.make(24,54,117));
        listBg.setSize(tabBg.getWidth()/2, tabBg.getHeight());
        listBg.align(null, Obj.Align.CENTER, 0, 0);
        listBg.setX(tabBg.getWidth()/2);

        listPage = new Page(listBg);
        listPage.setSize(listBg.getWidth(), listBg.getHeight());
        listPage.setBgOpa(Obj.PART_MAIN, Obj.State.DEFAULT, Obj.OPA_TRANSP);
        listPage.setPaddingTop(Obj.PART_MAIN, Obj.State.DEFAULT, 0);
        listPage.setPaddingLeft(Obj.PART_MAIN, Obj.State.DEFAULT, 0);
        listPage.setPaddingRight(Obj.PART_MAIN, Obj.State.DEFAULT, 0);
        listPage.setPaddingBottom(Obj.PART_MAIN, Obj.State.DEFAULT, 0);
        // listPage.setLayout(Cont.Layout.ROW_MID);

        wavBars = new ArrayList<Obj>();
        for (int i = 0; i < 400; i++) {
            Obj obj = new Obj(wavBg);
            obj.setSize(wavBg.getWidth() / 400 - 1, 10);
            obj.setBgColor(Obj.PART_MAIN, Obj.State.DEFAULT, Color.make(0xffff00));
            obj.setPosition((obj.getWidth() + 1) * i, 300);

            wavBars.add(obj);
        }
        updateList(System.getProperty("user.dir"));
    }

    public void updateList(String path) {
        System.out.println("Enter path:" + path);
        this.pathText.setText(path);
        int i = 0;

        File directory = new File(path);

        if (!directory.exists() || !directory.isDirectory()) {
            System.err.println("目录不存在或不可访问");
            String currentDir = System.getProperty("user.dir");
            updateList(currentDir);
            return;
        }
        File[] files = directory.listFiles();
        if (files == null) {
            System.err.println("目录不存在或不可访问");
            String currentDir = System.getProperty("user.dir");
            updateList(currentDir);
            return;
        }

        List<ListItem> newList = new ArrayList<ListItem>();
        for (i = 0; i < files.length; i++) {
            File file = files[i];
            ListItem item = new ListItem();
            item.name = file.getName();
            if (file.isDirectory()) {
                item.type = 2;
            } else {
                item.type = item.name.endsWith(".mp3") ? 0 : 1;
            }
            newList.add(item);
        }

        List<ListItem> newAudioList = new ArrayList<ListItem>();
        for (i = 0; i < newList.size(); i++) {
            ListItem item = newList.get(i);
            if (item.type == 0) {
                newAudioList.add(item);
            }
        }

        if (path.equals(this.playingPath)) {
            ListItem newPlayingItem = null;
            for (i = 0; i < newAudioList.size(); i++) {
                ListItem item = newAudioList.get(i);
                if (item.name.equals(playItem.name)) {
                    newPlayingItem = item;
                    break;
                }
            }
            if (newPlayingItem == null) {
                if (this.audioPlayer == null) {
                    this.audioPlayer.destroy();
                    this.audioPlayer = null;   
                }
                this.playItem = null;
                this.playList = null;
                this.playAudioList = null;
                this.playingPath = null;
            } else {
                this.playList = newList;
                this.playAudioList = newAudioList;
                this.playItem = newPlayingItem;
            }
        }
        if (this.dispList != null) {
            for (i = 0; i < this.dispList.size(); i++) {
                ListItem item = dispList.get(i);
                item.delete();
            }
        }
        this.dispList = newList;
        this.dispAudioList = newAudioList;
        this.currentPath = path;
        
        for (i = 0; i < this.dispList.size(); i++) {
            ListItem item = this.dispList.get(i);

            item.bg = new Cont(listPage);
            item.bg.setBgOpa(Obj.PART_MAIN, Obj.State.DEFAULT, Obj.OPA_TRANSP);
            item.bg.setBgOpa(Obj.PART_MAIN, Obj.State.PRESSED, Obj.OPA_COVER);
            item.bg.setBgColor(Obj.PART_MAIN, Obj.State.PRESSED, Color.make(45,70,123));
            item.bg.setSize(listPage.getWidthFit(), 25);
            item.bg.setPosition(0, i * 25);
            item.bg.setClick(true);
            listPage.glueObj(item.bg, true);
            item.bg.setEventListener(this);

            item.nameLabel = new Label(item.bg);
            item.nameLabel.setText(item.name);
            item.nameLabel.align(null, Obj.Align.IN_LEFT_MID, 10, 0);
            item.nameLabel.setTextColor(Color.make(89, 140, 37));
            item.nameLabel.setTextFont(Label.PART_MAIN, Obj.State.DEFAULT, Font.defaultFont(12, null));
        }

        if (this.playItem != null) {
            this.playItem.setPlayingStyle(true);
        }
    }

    public void playAudio(ListItem listItem, int id) {
        int i;
        String path = currentPath + "/" + listItem.name;
        File file = new File(path);
        if (null != audioPlayer) {
            audioPlayer.destroy();
            audioPlayer = null;
        }
        if (this.playItem != null) {
            this.playItem.setPlayingStyle(false);
        }
        this.playItem = listItem;
        this.playingPath = this.currentPath;

        if (listItem != null) {
            listItem.setPlayingStyle(true);
        }
        
        audioPlayer = new AudioPlayer(path);
        audioPlayer.load();
        audioPlayer.setListener(this);
        startAutomate = true;
    }

    @Override
    public void onEvent(Obj obj, Event event) {
        if (event == Event.SHORT_CLICKED) {
            if (obj == this.slider) {
                if (audioPlayer == null) return;
                
            }
            if (obj == this.prevBtn) {
                if (audioPlayer == null) return;
                
            }
            if (obj == this.nextBtn) {
                if (audioPlayer == null) return;
                
            }
            if (obj == this.playBtn) {
                if (audioPlayer == null) return;
                AudioPlayer.State state = audioPlayer.getState();
                switch (state) {
                    case IDLE:
                        break;
                    case LOADING:
                        break;
                    case PLAYING:
                        startAutomate = false;
                        audioPlayer.pause();
                        break;
                    case PAUSED:
                        audioPlayer.resume();
                        break;
                    default:
                        break;
                }
                updatePlayBtn();
            }
            if (obj == this.listBtn) {
                this.tabBg.setX(-this.tabBg.getWidth()/2);
            }
            if (obj == this.wavBtn) {
                this.tabBg.setX(0);
            }
            if (obj == this.retBtn) {
                String path = currentPath.replaceAll("/+$", "");
                path = path.replaceAll("/[^/]+$", "");
                updateList(path);
            }
            if (obj == this.okBtn) {
                updateList(this.pathText.getText());
            }

            int i;
            for (i = 0; i < this.dispList.size(); i++) {
                ListItem listItem = this.dispList.get(i);
                if (listItem.bg != obj) continue;
                switch (listItem.type) {
                    case 0:
                        playAudio(listItem, i);
                        break;
                    case 1:
                        break;
                    case 2:
                        this.updateList(currentPath + "/" + listItem.name);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    public void updatePlayBtn() {
        AudioPlayer.State state = AudioPlayer.State.IDLE;
        if (null != audioPlayer) state = audioPlayer.getState();
        String playIcon = "";
        switch (state) {
            case IDLE:
                playIcon = "ic_play.png";
                break;
            case LOADING:
                playIcon = "ic_play.png";
                break;
            case PLAYING:
                playIcon = "ic_pause.png";
                break;
            case PAUSED:
                playIcon = "ic_play.png";
                break;
            default:
                break;
        }
        PicSrc src = PictureLoader.loadFitDPI(Main.app, playIcon);
        playBtn.setSrc(src);
        titleLabel.setText(this.playItem.name);
    }

    @Override
    public void onStateChanged(AudioPlayer player) {
        AudioPlayer.State state = player.getState();
        switch (state) {
            case IDLE:
                break;
            case LOADING:
                break;
            case PLAYING:
                break;
            case PAUSED:
                if (startAutomate) {
                    player.resume();
                }
                break;
            default:
                break;
        }
        updatePlayBtn();
    }
    public void onSpectrum(AudioPlayer player, int[] spec, int N) {
        int i;
        final  int rate = 16000;
        String t = "";
        for (i = 0; i < N; i++) {
            // if (spec[i] > 2)
                // System.out.println(i*rate/N +"Hz :" + spec[i]);
        }
        if (wavBars.size() > N) {
            for (i = 0; i < wavBars.size(); i++) {
                Obj w = wavBars.get(i);
                int v = i * N / wavBars.size();
                w.setPosition(w.getX(), (w.getY() + w.getHeight() - spec[v])/2);
                w.setSize(w.getWidth(), spec[v]);
            }
        } else {
            int sum = 0;
            int sumCnt = 0;
            int barId = 0;
            for (i = 0; i < N; i++) {
                int v = i * wavBars.size() / N;
                if (v == barId) {
                    sum += spec[i];
                    sumCnt++;
                } else {
                    Obj w = wavBars.get(barId);
                    w.setPosition(w.getX(), w.getParent().getHeight()/2 - sum);
                    w.setSize(w.getWidth(), sum*2);

                    sum = spec[i];
                    barId = v;
                }
            }
        }
    }
    public boolean onKeyEvent(int keyCode, boolean pressed) {
        
        if (keyCode == Disp.LV_KEY_SCROLL_UP && !pressed) {
            listPage.setAnimTime(20);
            listPage.scrollVer(30);
            return true;
        }
        if (keyCode == Disp.LV_KEY_SCROLL_DOWN && !pressed) {
            listPage.setAnimTime(20);
            listPage.scrollVer(-30);
            return true;
        }
        if (keyCode == Disp.LV_KEY_SCROLL_UP || keyCode == Disp.LV_KEY_SCROLL_DOWN)
            return true;
        return false;
    }
}
